import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Table,
  Tag,
  Space,
  Modal,
} from 'antd';
import defaultImg from 'assets/error.png';
import { getChannels } from 'api/channel';
import { getArticles, deleteArticle } from 'api/articles';
import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import history from 'utils/history';
import Channel from 'components/Channel';
const { confirm } = Modal;
export default function ArticleList() {
  //   状态值处理
  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      //   自定义渲染内容,封面处理
      render: (cover) => {
        return (
          <img
            src={cover.images.length ? cover.images[0] : defaultImg}
            alt=""
            style={{ width: 100, height: 60, objectFit: 'cover' }}
          />
        );
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status) => {
        const obj = articleStatus.find((v) => v.id === status);
        return <Tag color={obj.color}>{obj.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      key: 'action',
      render: (value, row) => {
        return (
          <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => handleEdit(row.id)}
            ></Button>
            <Button
              type="primary"
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => handleDelete(row.id)}
            ></Button>
          </Space>
        );
      },
    },
  ];
  // 文章对象(包含总条数,分页信息等)
  const [article, setArticle] = useState({});
  //   获取文章列表
  const getArticlesList = async (params = {}) => {
    const res = await getArticles(params);
    // console.log(res);
    setArticle(res.data);
  };
  //   组件挂载时触发
  useEffect(() => {
    //   调用获取频道,封装过了
    // 获取文章列表
    getArticlesList();
  }, []);
  // 1️⃣创建一个 ref 对象，用于存放 query 数据，方便在不同的函数内存值或取值
  const queryRef = useRef({});
  //   筛选提交表单提交渲染不同数据
  const onFinish = async ({ status, channel_id, date }) => {
    console.log(status, channel_id, date);
    // 请求查询参数
    let query = {};
    // 文章状态
    query.status = status !== -1 ? status : undefined;
    // 频道id
    query.channel_id = channel_id;
    // 日期,作格式化处理
    if (date) {
      // 需要把 Moment 对象格式化成字符串
      query.begin_pubdate = date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      query.end_pubdate = date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss');
    }
    // query.page = 1;
    query.per_page = article.per_page;
    // 统一删除掉undefined的值
    // for (const key in query) {
    //   if (query[key] === undefined) {
    //     //   delete删除对象的键
    //     delete query[key];
    //   }
    // }
    //统一删除掉undefined的值
    query = JSON.parse(JSON.stringify(query));
    console.log(query);
    const res = await getArticles({ ...query, page: 1 });
    console.log(153, res);
    setArticle(res.data);
    // 2️⃣把表单获取的参数存储到 ref 对象中，在分页器函数中获取
    queryRef.current = query;
  };
  //   分页页码改变渲染数据
  const pageChange = async (page, pageSize) => {
    const res = await getArticles({
      // 把表单筛选的参数拼接到分页器上
      ...queryRef.current,
      page,
      per_page: pageSize,
    });
    // console.log(res);
    setArticle(res.data);
  };

  //   删除文章
  const handleDelete = (id) => {
    // console.log(id);
    // console.log(article.page);
    confirm({
      title: '温馨提示?',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除文章吗',
      onText: '删除',
      onType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        //   发请求删除
        await deleteArticle(id);
        // console.log(res);
        // console.log(queryRef.current);
        // 更新列表
        getArticlesList({
          ...queryRef.current,
          page: article.page,
          per_page: article.per_page,
        });
      },
    });
  };
  //   修改文章
  const handleEdit = (id) => {
    // console.log(id);
    history.push(`/edit/${id}`, { id });
  };
  return (
    <div className="root">
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          autoComplete="off"
          initialValues={{ status: -1 }}
          onFinish={onFinish}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="频道" name="channel_id">
            <Channel allowClear></Channel>
          </Form.Item>
          <Form.Item label="日期" name="date">
            <DatePicker.RangePicker />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        {/* 筛选结果标题 */}
        <h3>根据筛选条件共查询到 {article.total_count} 条结果：</h3>
        {/* 表格组件 */}
        <Table
          dataSource={article.results}
          columns={columns}
          rowKey="id"
          pagination={{
            // 控制位置
            position: ['bottomCenter'],
            // 控制总条数
            total: article.total_count,
            // 页面改变触发的回调函数
            onChange: pageChange,
            current: article.page,
            pageSize: article.per_page,
          }}
        />
      </Card>
    </div>
  );
}
